
#import "DnpLoading.h"
#import <MBProgressHUD/MBProgressHUD.h>

@interface DnpLoading()
@property (nonatomic, strong) MBProgressHUD *loadingHud;
@end

@implementation DnpLoading

+ (instancetype)shareInstance {
    static DnpLoading *instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[self alloc] init];
    });
    return instance;
}

- (void)open {
        
    self.loadingHud = [MBProgressHUD showHUDAddedTo:[self topW] animated:YES];

    self.loadingHud.mode = MBProgressHUDModeIndeterminate;

    self.loadingHud.bezelView.style = MBProgressHUDBackgroundStyleSolidColor;
    
    self.loadingHud.bezelView.backgroundColor = [[UIColor alloc]initWithRed:62/255 green:62/255 blue:62/255 alpha:1.0];

    self.loadingHud.contentColor = [UIColor whiteColor];

    self.loadingHud.backgroundView.style = MBProgressHUDBackgroundStyleSolidColor;
    
    [self.loadingHud.bezelView addConstraint:
                 [NSLayoutConstraint constraintWithItem:self.loadingHud.bezelView
                                              attribute:NSLayoutAttributeWidth
                                              relatedBy:NSLayoutRelationEqual
                                                 toItem:nil
                                              attribute:NSLayoutAttributeNotAnAttribute
                                             multiplier:1
                                               constant:105]];
    
    [self.loadingHud.bezelView addConstraint:
                 [NSLayoutConstraint constraintWithItem:self.loadingHud.bezelView
                                              attribute:NSLayoutAttributeHeight
                                              relatedBy:NSLayoutRelationEqual
                                                 toItem:nil
                                              attribute:NSLayoutAttributeNotAnAttribute
                                             multiplier:1
                                               constant:84]];
}

- (void)close {
    [self.loadingHud hideAnimated:YES];
}

- (UIWindow *)topW {
    if (@available(iOS 13.0, *)) {
        for (UIWindowScene *wsc in [UIApplication sharedApplication].connectedScenes) {
            if (wsc.activationState == UISceneActivationStateForegroundActive) {
                for (UIWindow *win in wsc.windows) {
                    if (win.isKeyWindow) {
                        return win;
                    }
                }
            }
        }
    }
    return [UIApplication sharedApplication].keyWindow;
}

@end
